/**
 * @date: 2025/3/22
 * @fileName: user
 * @Description: 用户状态
 */
import { acceptHMRUpdate, defineStore } from 'pinia'
import type { TenantEntity, UserInfoEntity } from '@/entity/UserEntity.ts'
import { ApiUserInfo } from '@/api/system/user.ts'

interface UserState {
  userInfo: Nullable<UserInfoEntity>
  tenant?: Nullable<TenantEntity>
  tenantList?: TenantEntity[]
}

export const useUserStore = defineStore('app-user', {
  state: (): UserState => ({
    userInfo: null,
    tenant: null,
    tenantList: [],
  }),

  actions: {
    /**
     * 设置当前租户信息
     * @param tenant
     */
    setTenant(tenant: TenantEntity) {
      this.tenant = tenant
    },

    /**
     * 设置租户列表
     * @param tenantList
     */
    setTenantList(tenantList: TenantEntity[]) {
      this.tenantList = tenantList
    },

    /**
     * 设置用户信息
     * @param userInfo
     */
    setUserInfo(userInfo: UserInfoEntity) {
      this.userInfo = userInfo
    },

    /**
     * 获取用户信息
     */
    async getUserInfo() {
      const user = await ApiUserInfo()
      this.setUserInfo(user)
    },
  },
  persist: {
    pick: ['userInfo', 'tenant', 'tenantList'],
  },
})

// 解决热更新问题
const hot = import.meta.hot
if (hot) {
  hot.accept(acceptHMRUpdate(useUserStore, hot))
}
